package jh.com.jhappbf.weight.query;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.blankj.utilcode.util.TimeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.ExpressionUtils;
import jh.com.jhappbf.utils.FileImport;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.work.WorkSettingActivity;

/**
 * @author : wwh
 * e-mail  : 953889276@qq.com
 * time    : 2019-7-8 9:55:34
 * desc    :
 */
public class TruckQueryActivity extends AbActivity {

    @BindView(R.id.query_weight_title)
    LinearLayout mListViewHeader;// 数据标题
    @BindView(R.id.query_listView)
    ListView mListView;// 数据列表
    @BindView(R.id.query_pullToRefreshView)
    AbPullToRefreshView mRefreshView;// 下拉刷新上拉加载更多
    @BindView(R.id.query_weight_content)
    RelativeLayout mContentView;// 显示的数据列表的视图
    @BindView(R.id.query_weight_error_refresh_img)
    ImageView queryWeightErrorRefreshImg;
    @BindView(R.id.query_weight_error_txt)
    TextView queryWeightErrorTxt;
    @BindView(R.id.query_weight_error_btn)
    Button mBtnErrRefresh;// 重试
    @BindView(R.id.query_weight_error_view)
    RelativeLayout mErrorContentView;// 网络不给力显示的视图
    @BindView(R.id.query_weight_views)
    RelativeLayout queryWeightViews;

    @BindView(R.id.query_weight_export_excel_layout)
    RelativeLayout mExportExcel;

    private List<JSONObject> mData = new ArrayList<>(); //数据源
    private List<JSONObject> mDataSource = new ArrayList<>(); //数据源的备份
    private MyBaseAdapter mAdapter; //数据列表适配器
    private AbLoadDialogFragment mDialogFragment = null; //进度框
    private List<String> mFields = new ArrayList<>();
    private List<String> mSaverFields = new ArrayList<>();
    private int mCurrentScreenWidth = 80;//默认列表宽度
    private Drawable mLeftDrawable; //列表单元格边框
    private Drawable mHeadDrawable;//列表头下拉框
    private int mCurrentPage = 0;//当前页数
    private int mPageSize = 100; //当前页的大小

    private List<TextView> mTitleTxt = new ArrayList<>(); //列表的表头view
    private ArrayList<String> mSelectData = new ArrayList<>();
    private List<JSONObject> newListData = new ArrayList<>();
    private Map<String, String> mFieldsMap;
    private String mStartTime = "";
    private String mStartDate = "";
    private String mEndTime = "";
    private String mEndDate = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_truck_query);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText("查询");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        View rightViewMore = mInflater.inflate(R.layout.title_right_btn, null);
        mAbTitleBar.addRightView(rightViewMore);
        Button mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_btn);
        mTitleRightBtn.setOnClickListener(v -> {
            Intent intent = new Intent(TruckQueryActivity.this, WorkSettingActivity.class);
            startActivityForResult(intent, 0x0001);
        });

        Intent intent = getIntent();
        if (intent != null) {
            mStartDate = intent.getStringExtra("startDate");
            mStartTime = intent.getStringExtra("startTime");
            mEndDate = intent.getStringExtra("endDate");
            mEndTime = intent.getStringExtra("endTime");
        }
        mFieldsMap = new LinkedHashMap<>();
        mFieldsMap.put("序号", "orderNum");
//        mFieldsMap.put("编号", "id");
        mFieldsMap.put("车号", "Platenumber");
        mFieldsMap.put("类型", "Type");
        mFieldsMap.put("货名", "Cargoname");
        mFieldsMap.put("等级", "Specification");
        mFieldsMap.put("发货", "Consignor");
        mFieldsMap.put("收货", "Consignee");
        mFieldsMap.put("货车司机", "S33");
        mFieldsMap.put("毛重", "Gross");
        mFieldsMap.put("皮重", "Tare");
        mFieldsMap.put("净重", "Net");

        for (Entry<String, String> entry : mFieldsMap.entrySet()) {
            mFields.add(entry.getKey());
            mSaverFields.add(entry.getValue());
        }

        WindowManager wm = getWindowManager();
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
//		mCurrentScreenWidth =60;// (metrics.widthPixels)/(10 + 1);
        mLeftDrawable = ContextCompat.getDrawable(this, R.mipmap.table_line);
        mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(), mLeftDrawable.getMinimumHeight());
        mHeadDrawable = ContextCompat.getDrawable(this, R.mipmap.down_select);
        mHeadDrawable.setBounds(0, 0, mHeadDrawable.getMinimumWidth(), mHeadDrawable.getMinimumHeight());
// 下拉刷新
        mRefreshView.setOnHeaderRefreshListener(view -> refreshTask());

        // 上拉加载更多
        mRefreshView.setOnFooterLoadListener(view -> loadMoreTask());

        // 单击数据项
        mListView.setOnItemClickListener((parent, view, position, id) -> {
        });

        //长按列表显示称重的详细信息
        mListView.setOnItemLongClickListener((parent, view, position, id) -> {
            Intent i = new Intent(this, QueryWeightDetail.class);
            JSONObject obj = mData.get(position);
            String weightId = obj.optString("id");
            i.putExtra("flag", weightId);
            startActivity(i);
            return true;
        });

        // 设置进度条的样式
        mRefreshView.getHeaderView().setHeaderProgressBarDrawable(
                ContextCompat.getDrawable(this, R.drawable.progress_circular));
        mRefreshView.getFooterView().setFooterProgressBarDrawable(
                ContextCompat.getDrawable(this, R.drawable.progress_circular));

        // 生成数据列表表头
        makeHeader();

        // 加载数据
        loadFirst();

        // 绑定ListView的Adapter
        mAdapter = new MyBaseAdapter();
        mListView.setAdapter(mAdapter);
        //    getWorkInfo();
    }

    /**
     * 第一次加载
     */
    private void loadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> {
            mErrorContentView.setVisibility(View.GONE);
            mContentView.setVisibility(View.VISIBLE);
            refreshTask();
        });
    }


    /**
     * 制作表头
     */
    private void makeHeader() {
        TableLayout table = new TableLayout(this);
        TableRow row = new TableRow(this);
        String columnName;
        for (int index = 0; index < mFields.size(); index++) {
            TextView textView = new TextView(this);
            setColumnWidth(mFields.get(index), textView);
            textView.setTextColor(Color.BLACK);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
            textView.setGravity(Gravity.CENTER);
            textView.setPadding(1, 10, 0, 10);
            textView.setId(index);
            columnName = mFields.get(index);
            textView.setText(columnName);
            textView.setTag(columnName);
            textView.setClickable(true);
            mTitleTxt.add(textView);
            textView.setOnClickListener(this::popupWindow);
            textView.setCompoundDrawables(mLeftDrawable, null, null, null);
            textView.setCompoundDrawables(null, null, mHeadDrawable, null);
            row.addView(textView);
        }
        table.addView(row);
        mListViewHeader.addView(table);
    }

    private void setColumnWidth(String columnName, TextView textView) {
        switch (columnName) {
            case "货名":
            case "车号":
            case "类型":
                textView.setWidth((int) (mCurrentScreenWidth * 2.5));
                break;
            case "发货":
            case "收货":
                textView.setWidth((int) (mCurrentScreenWidth * 3.5));
                break;
            case "原发净重":
            case "实收净重":
                textView.setWidth(mCurrentScreenWidth * 3);
                break;
            case "毛重时间":
            case "皮重时间":
                textView.setWidth(mCurrentScreenWidth * 4);
                break;
            default:
                textView.setWidth(mCurrentScreenWidth * 2);
                break;
        }
    }

    /**
     * 弹出选择框
     *
     * @param v 当前View
     */
    private void popupWindow(View v) {
        if (v instanceof TextView) {
            final TextView txt = (TextView) v;
            String columnName = (String) txt.getTag();
            String columnFiled = mFieldsMap.get(columnName);
            if (!TextUtils.isEmpty(columnFiled)) {
                mSelectData.clear();
                mSelectData.add(columnName);
                String item;
                for (int index = 0; index < mDataSource.size(); index++) {
                    item = mDataSource.get(index).optString(columnFiled);
                    if (!mSelectData.contains(item)) {
                        mSelectData.add(item);
                    }
                }
                new AlertDialog.Builder(TruckQueryActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                        .setTitle(columnName + "选择")
                        .setItems(mSelectData.toArray(new String[0]), (dialog, which) -> {
                            txt.setText(mSelectData.get(which));
                            filterData();
                        }).create().show();
            }

        }
    }

    @OnClick({R.id.query_weight_error_btn,R.id.query_weight_export_excel_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.query_weight_error_btn:
            loadFirst();
            break;
            case R.id.query_weight_export_excel_layout:
                boolean result = FileImport.generateExcel("内部车辆查询", mData, mSaverFields, mFields);
                if(result){
                    Toast.makeText(this, "导出成功", Toast.LENGTH_SHORT).show();
                }
                break;
            default:

        }

    }

    /**
     * 下拉刷新
     */
    private void refreshTask() {
        String methodName = "truckQuery";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("currentPage");
        param.add("startDateTime");
        param.add("endDateTime");
        param.add("user");
        param.add("admin");
        mCurrentPage = 1;
        value.add(Integer.toString(mCurrentPage));
        if (mStartDate.isEmpty() || mStartTime.isEmpty()) {
            mStartDate = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
            mStartTime = "00:00:00";
        }

        if (mEndDate.isEmpty() || mEndTime.isEmpty()) {
            mEndDate = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
            mEndTime = "23:59:59";
        }
        value.add(mStartDate + " " + mStartTime);
        value.add(mEndDate + " " + mEndTime);
        value.add(State.mAccount);
        if (State.mRight.contains("admin") || "gys".equals(State.mAccount)) {
            value.add("admin");
        } else {
            value.add("normal");
        }

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(this);
            mRefreshView.onHeaderRefreshFinish();
            mErrorContentView.setVisibility(View.GONE);
            mContentView.setVisibility(View.VISIBLE);
            newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null) {
                mDataSource.clear();
                mDataSource.addAll(newListData);
                if (mDataSource.size() > 0) {
                    if (mDataSource.size() >= mPageSize) {
                        mCurrentPage++;
                    }
                    filterData();
                }
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(this);
            mRefreshView.onHeaderRefreshFinish();
            mErrorContentView.setVisibility(View.VISIBLE);
            mContentView.setVisibility(View.GONE);
            mData.clear();
            mAdapter.notifyDataSetChanged();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);
    }

    /**
     * 上拉加载更多
     */
    private void loadMoreTask() {
        String methodName = "truckQuery";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("currentPage");
        param.add("startDateTime");
        param.add("endDateTime");
        param.add("user");
        param.add("admin");
        value.add(Integer.toString(mCurrentPage));
        value.add(mStartDate + " " + mStartTime);
        value.add(mEndDate + " " + mEndTime);
        value.add(State.mAccount);
        if (State.mRight.contains("admin") || "gys".equals(State.mAccount)) {
            value.add("admin");
        } else {
            value.add("normal");
        }
        Listener<String> listener = response -> {
            mRefreshView.onFooterLoadFinish();
            if (newListData.size() > 0 && newListData.size() < mPageSize) {
                if (mCurrentPage == 1) {
                    mDataSource.remove(0);
                }
//                mDataSource.remove(0);
                mDataSource.removeAll(newListData);
            }
            newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {

                mDataSource.addAll(newListData);
                if (newListData.size() == mPageSize) {
                    mCurrentPage++;
                }
                filterData();
            }
        };
        ErrorListener errorListener = error -> {
            mRefreshView.onFooterLoadFinish();
            AbToastUtil.showToast(this, "数据加载失败！");
        };
        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);
    }

    /**
     * 过滤数据源
     */
    private void filterData() {
        String valStr;
        String tagStr;
        Map<String, String> mHashMap = new HashMap<>();
        for (TextView txt : mTitleTxt) {
            valStr = txt.getText().toString();
            tagStr = (String) txt.getTag();
            if (!valStr.equals(tagStr)) {
                mHashMap.put(tagStr, valStr);
            }
        }
        if (mHashMap.size() > 0) {
            mData = new ArrayList<>();
            JSONObject mObject;
            float gross = 0;
            float tare = 0;
            float net = 0;
            for (int index = 0; index < mDataSource.size(); index++) {
                mObject = mDataSource.get(index);
                for (Entry<String, String> entry : mFieldsMap.entrySet()) {
                    if (mHashMap.containsKey(entry.getKey())) {
                        if (mObject.optString(entry.getValue()).equals(entry.getKey())) {
                            String grossStr = mObject.optString("Gross");
                            String tareStr = mObject.optString("Tare");
                            String netStr = mObject.optString("Net");
                            String plateNumber = mObject.optString("Platenumber");
                            if (!"合计".equals(plateNumber)) {
                                if (ExpressionUtils.isNumber(grossStr)) {
                                    gross += Float.parseFloat(grossStr);
                                }
                                if (ExpressionUtils.isNumber(tareStr)) {
                                    tare += Float.parseFloat(tareStr);
                                }
                                if (ExpressionUtils.isNumber(netStr)) {
                                    net += Float.parseFloat(netStr);
                                }
                            }
                            mData.add(mObject);
                        }
                    }
                }
            }

            try {
                JSONObject sumObject = new JSONObject();
                sumObject.put("Platenumber", "合计");
                sumObject.put("Cargoname", "车数:" + mData.size());
                sumObject.put("Specification", "");
                DecimalFormat format = new DecimalFormat("0.00");
                sumObject.put("Gross", format.format(gross));
                sumObject.put("Tare", format.format(tare));
                sumObject.put("Net", format.format(net));
                mData.add(sumObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mAdapter.notifyDataSetChanged();
        } else {
            mData = mDataSource;
            getSum();
            mAdapter.notifyDataSetChanged();
        }
    }

    ///总合计
    private void getSum() {
        JSONObject obj;
        float net = 0;
        float gross = 0;
        float tare = 0;
        for (int index = 0; index < mData.size(); index++) {
            obj = mData.get(index);
            String netStr = obj.optString("Net");
            String grossStr = obj.optString("Gross");
            String tareStr = obj.optString("Tare");
            if (obj.optString("Platenumber").contains("合计")) {
                continue;
            }
            if (ExpressionUtils.isNumber(netStr)) {
                net += Float.parseFloat(netStr);
            }
            if (ExpressionUtils.isNumber(grossStr)) {
                gross += Float.parseFloat(grossStr);
            }
            if (ExpressionUtils.isNumber(tareStr)) {
                tare += Float.parseFloat(tareStr);
            }
        }
        try {
            JSONObject sumObject = new JSONObject();
            sumObject.put("Platenumber", "合计");
            //      sumObject.put("Cargoname", "记录数:" + mData.size());
            if (mCurrentPage == 1) {
                sumObject.put("Cargoname", "车数:" + (mData.size()));
            } else if (mCurrentPage == 2 && newListData.size() == mPageSize) {
                sumObject.put("Cargoname", "车数:" + (mData.size()));
            } else {
                sumObject.put("Cargoname", "车数:" + (mData.size() - 1));
            }
            sumObject.put("Specification", "");
            DecimalFormat format = new DecimalFormat("0.00");
            sumObject.put("Net", format.format(net));
            sumObject.put("Gross", format.format(gross));
            sumObject.put("Tare", format.format(tare));
            if (mData.size() > 0) {
                JSONObject firstObj = mData.get(0);
                String val = firstObj.getString("Platenumber");
                if (val.contains("合计")) {
                    mData.remove(0);
                }
                mData.add(0, sumObject);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            mStartDate = data.getStringExtra("startDate");
            mStartTime = data.getStringExtra("startTime");
            mEndDate = data.getStringExtra("endDate");
            mEndTime = data.getStringExtra("endTime");
            loadFirst();
        }
    }

    private class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {

            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            TableLayout table;
            if (convertView == null) {
                Context context = TruckQueryActivity.this;
                table = new TableLayout(context);
                TableRow row = new TableRow(context);
                Drawable mItemSelect = ContextCompat.getDrawable(context, R.drawable.list_item_bg);
                row.setBackground(mItemSelect);
                row.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
                for (int index = 0; index < mFields.size(); index++) {
                    TextView textView = new TextView(context);
                    setColumnWidth(mFields.get(index), textView);
                    textView.setTextColor(Color.BLACK);
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
                    textView.setGravity(Gravity.CENTER);
                    textView.setPadding(1, 0, 1, 0);
                    textView.setId(index);
                    textView.setCompoundDrawables(mLeftDrawable, null, null, null);
                    row.addView(textView);
                }
                table.addView(row);
                convertView = table;
                convertView.setTag(table);
            } else {
                table = (TableLayout) convertView.getTag();
            }
            JSONObject obj = mData.get(position);
            int length = mSaverFields.size();
            //显示表格的一行数据
            for (int i = 0; i < length; i++) {
                TextView textView = table.findViewById(i);
                if (i == 0) {
                    textView.setText(position + "");
                } else {
                    textView.setText(obj.optString(mSaverFields.get(i)));
                }
            }

            return convertView;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
